//
//  WaterFlowLayout.m
//  UI20_瀑布流
//
//  Created by dllo on 15/7/2.
//  Copyright (c) 2015年 蓝欧科技. All rights reserved.
//

#import "WaterFlowLayout.h"

@interface WaterFlowLayout ()
{
    float oringinY[100];
    float cellHeight[100];
    
    float h1;
    float h2;
    float h3;
}

@property (nonatomic, retain) NSMutableArray *arr;

@end

@implementation WaterFlowLayout

// 准备瀑布流
- (void)prepareLayout {
    [super prepareLayout];
    
    for (int i = 0; i < 12; i++) {
        cellHeight[i] = arc4random() % 50 + 180;
    }
    
}

- (CGSize)collectionViewContentSize {
    
    long n = [self.collectionView numberOfItemsInSection:0];
    
    h1 = h2 = h3 = 0;
    for (int i = 0; i < n; i++) {
        switch (i % 3) {
            case 0:
                h1 += cellHeight[i] + 10;
                break;
                
            case 1:
                h2 += cellHeight[i] + 10;
                break;
                
            case 2:
                h3 += cellHeight[i] + 10;
                break;
                
            default:
                break;
        }
    }
    
    float height = MAX(MAX(h1, h2), h3) + 20;
    
    return CGSizeMake(375, height);
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewLayoutAttributes *layoutAttribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    CGRect rect = layoutAttribute.frame;
    rect.origin.x = (indexPath.item % 3) * ((375 - 10) / 3) + 10;
    
    if (indexPath.item >= 3) {
        rect.origin.y = oringinY[indexPath.item - 3] + cellHeight[indexPath.item - 3] + 10;
    } else {
        rect.origin.y = 20;
    }
    rect.size.width = (375 - 40) / 3;
    rect.size.height = cellHeight[indexPath.item];
    
    layoutAttribute.frame = rect;
    
    oringinY[indexPath.item] = layoutAttribute.frame.origin.y;
    
    
    //NSLog(@"num:%ld\nx:%f\ny:%f\nw:%f\nh:%f\n", (long)indexPath.item, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
    
    
    return layoutAttribute;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    
    NSArray *arr = [super layoutAttributesForElementsInRect:rect];
    if ([arr count] > 0) {
        return arr;
    }
    NSMutableArray *attributes = [NSMutableArray array];
    for (NSInteger i = 0 ; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        [attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
    }
    return attributes;
}

@end
